package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.myhttp.CallBackString;
import com.example.myhttp.Ihttp;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.ParentMsg;
import com.ohuang.jiaxiaotong.entity.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

//家长编辑个人信息界面
public class fillUserMsg2Activity extends BaseAc {
    private ImageView imageView_bg, imageView_icon;
    private EditText editText_name, editText_phone, editText_child;
    private View view_setBg;
    private TextView textView_userName;
    private User user;
    private static final int READ_REQUEST_CODE = 42;
    private String txt_name, txt_phone, txt_child;
    private static final int SI_SUCCESS = 0, SI_FAIL = 1, SI_ERROR = 2, SI_OTHER = 3;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fill_user_msg2);
        EventBus.getDefault().register(this);//注册EventBus
        setTitle("个人信息");
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮

        initData();
        HttpGetParent();
    }


    private void initData() {
        imageView_bg = findViewById(R.id.img_bg_fillUserMsg2);
        imageView_icon = findViewById(R.id.img_icon_fillUserMsg2);
        textView_userName = findViewById(R.id.txt_username_fillUserMsg2);
        editText_name = findViewById(R.id.edit_name_fillUserMsg2);
        editText_phone = findViewById(R.id.edit_phone_fillUserMsg2);
        editText_child = findViewById(R.id.edit_child_fillUserMsg2);
        view_setBg = findViewById(R.id.view_setBG_fillUserMsg2);

        if (user != null) {
            textView_userName.setText(user.getUsername());
        }
        String stringUri = Sys.ReadSharedPer(this, "bgUri", "");

        if (stringUri.isEmpty()) {
            //背景
            Glide.with(this).load(R.drawable.img_bg)
                    .into(imageView_bg);
        } else {
            //背景
            Uri uri = Uri.parse(stringUri);
            Glide.with(this).load(uri).error(R.drawable.img_bg).into(imageView_bg);
        }
        //头像
        Glide.with(this).load(user.getUrl()).error(R.drawable.img_icon)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(imageView_icon);

        view_setBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Sys.isClick()) {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(intent, READ_REQUEST_CODE);
                }
            }
        });

    }


    public void goToFillClick2(View view) {
        if (Sys.isClick()) {
            txt_child = editText_child.getText().toString();
            txt_name = editText_name.getText().toString();
            txt_phone = editText_phone.getText().toString();
            dialogLoading = Ohuang.dialogLoadingshow(fillUserMsg2Activity.this, "正在提交");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                        HttpSubmit();//提交数据
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private void HttpSubmit() {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("parentName", txt_name);
        map.put("childName", txt_child);
        map.put("iphone", txt_phone);
        Ihttp.getInstance().post(MyHttpURL.mainUrl + "parent/fillMsg", map, new CallBackString() {
            @Override
            public void fail(String s) {
                myHandler.sendEmptyMessage(SI_ERROR);
            }
            @Override
            public void success(String ojb) {
                if ("success".equals(ojb)) {
                    myHandler.sendEmptyMessage(SI_SUCCESS);
                } else if ("error".equals(ojb)) {
                    myHandler.sendEmptyMessage(SI_FAIL);
                } else {
                    myHandler.sendEmptyMessage(SI_OTHER);
                }
            }
        });

    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SI_SUCCESS:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(fillUserMsg2Activity.this, "提交成功", "个人信息已更改成功", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case SI_FAIL:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(fillUserMsg2Activity.this, "提交失败", "个人信息提交失败");
                    break;
                case SI_ERROR:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(fillUserMsg2Activity.this, "提交失败", "网络连接错误");
                    break;
                case SI_OTHER:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(fillUserMsg2Activity.this, "提交失败", "返回值错误");
                    break;

            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent resultData) {

        // The ACTION_OPEN_DOCUMENT intent was sent with the request code
        // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
        // response to some other intent, and the code below shouldn't run at all.

        super.onActivityResult(requestCode, resultCode, resultData);
        if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            // The document selected by the user won't be returned in the intent.
            // Instead, a URI to that document will be contained in the return intent
            // provided to this method as a parameter.
            // Pull that URI using resultData.getData().
            Uri uri = null;
            if (resultData != null) {
                uri = resultData.getData();

                Glide.with(this).load(uri)
                        .into(imageView_bg);

                Sys.WriteSharedPer(this, "bgUri", uri.toString());
            }
        }
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
        if (user != null && textView_userName != null && imageView_icon != null) {
            textView_userName.setText(user.getUsername());
            //头像
            Glide.with(this).load(user.getUrl()).error(R.drawable.img_icon)

                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))

                    .into(imageView_icon);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void HttpGetParent() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl + "user/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        service.getParent(map).enqueue(new Callback<ParentMsg>() {
            @Override
            public void onResponse(Call<ParentMsg> call, Response<ParentMsg> response) {
                editText_name.setText(response.body().getParentName());
                editText_child.setText(response.body().getChildName());
                editText_phone.setText(response.body().getIphone());
            }

            @Override
            public void onFailure(Call<ParentMsg> call, Throwable t) {

            }
        });

    }

    interface GithubService {
        //https://api.github.com/repos/{owner}/{repo}/contributors
        @POST("findParentMsg")
        Call<ParentMsg> getParent(@QueryMap HashMap<String, String> deviceInfo);
    }
}
